cap drop thebidder
cap program drop rddelta1x_binscatter_s
program rddelta1x_binscatter_s, rclass
	args id st_fy en_fy gname gtitle msz st_mdybid ed_mdybid graphtableop bwselector color01 nquantiles
	pause on 
	preserve
		*cap drop thebidder
		sort thebidder ad_firm
		local firmNM = nm_firm[1]
		local firmRG = region[1]
		local firmAD = ad_firm[1]
		local firmID = firmID[1]
		if "`color01'" == "color"{
			local mcolor0 = "navy"
			local mcolor1 = "cyan"
			local lcolor = "orange"
			local graphregioncolor = ""
		}
		else{
			local mcolor0 = "gs5%80"
			local mcolor1 = "gs5%80"
			local lcolor = "gs10%75"
			local graphregioncolor = "white"
		}
		
		di as result "### `firmNM';id:`id';`firmPR'`firmCT'; bhat=`est', t=`ts' ###"
		cap drop theauction
		qui bys id: egen theauction = max( thebidder == 1 )
		/*count if theauction == 1 & fy_con >= `st_fy' & fy_con <= `en_fy' */
		qui keep if (theauction == 1 | rank1_s == 1 ) & fy_con >= `st_fy' & fy_con <= `en_fy'  & FLAG == 0 /*used in survey*/
		qui keep if (theauction == 1 | rank1_s == 1 ) & MDYbid >= `st_mdybid' & MDYbid <= `ed_mdybid' & FLAG == 0 /*used in paper*/
		/* Do not include auctions in which (tie`z'`k' == 1) highest scores/prices are tie*/
		/* scoreが同率の1位と2位の者の価格bidは通常違うので、一位をどちらの業者にするかで2位以下の者すべての価格乖離率dep`z'sが変わり、RDの結果が変わるのを防ぐため
		なお、set seed 1では解決にならないのは、サンプルが変わって、行の番号が変わると同率の1位と2位の者のどちらをrank1_s = 1にするかは変化するから*/
		local leftright = "l"
		qui replace ldelta1p_s = -ldelta1s_s if rank1_s == 1
		*scatter ldelta1p_s ldelta1s_s
		
		qui count
		*di "cccccc td(`st_mdybid') td(`ed_mdybid') `r(N)' cccccc"
		local success = 0
		local drop = 0
		while `success' == 0 {				
		    qui sum ldelta1s_s if tie1s ~= 1 & (ldelta1s_s < 0 |  ldelta1s_s > `drop')
			cap noisily rdbwselect2a ldelta1p_s ldelta1s_s `leftright' ///
				if tie1s ~= 1 & (ldelta1s_s < 0 | ldelta1s_s >= `drop'), kernel(tri) vce(cluster id) bwselect(`bwselector')
			cap noisily rdrobust ldelta1p_s ldelta1s_s if tie1s ~= 1 , vce(cluster id) kernel(tri) 	///
						h(`e(h_`bwselector'_l)' `e(h_`bwselector'_r)') b(`e(b_`bwselector'_l)' `e(b_`bwselector'_r)')
			if _rc == 0 {
				local success = 1
				di "dropping samples to the right of zero"
				*continue, break
			}
			else if `drop' > 0.01{
				di "### drop if d(`runningvar', 0) < `drop' for rank1 bidder ###"
				local success = 1
				*continue, break	
			}
			else{
				local drop = `drop' + .001
			}
		}
		if `success' == 1 {			
			local est1s = string(`e(tau_bc_l)', "%6.3f" )
			mat Bl = e(V_rb_l)
			mat Br = e(V_rb_r)
			local se1s = string(sqrt(Bl[1,1]), "%6.3f" )
			local ts1s = string(`e(tau_bc_l)' / sqrt(Bl[1,1]) , "%6.3f" )
			local h = string(`e(h_l)' , "%6.3f" )
			di "**** est:" `e(tau_bc)'
			di "**** est_l:" `e(tau_bc_l)'
			di "**** est_r:" `e(tau_bc_r)'
			di "**** se_l:" sqrt(Bl[1,1])
			di "**** se_r:" sqrt(Br[1,1])
			di "**** tstat:" `ts1s'
			di "#### N:" `e(N_l)'
			eststo rd

			cap graph drop `gname'
			if "`ii'" != "nograph" {	
				qui binscatter ldelta1p_s ldelta1s_s if abs(ldelta1s_s) <= .1 & tie1s ~= 1 ///
					& rank1_s > 1, line(none) ///
					savedata(bins_temp) replace nquantiles(`nquantiles')
				tempfile __temp
				sleep 500

				*pause
				save `__temp', replace
				import delimited using bins_temp.csv, varnames(1) delimiters(",") clear
				erase "bins_temp.do"
				erase bins_temp.csv
				save bins_temp, replace
				sleep 500
				use `__temp', clear
				append using bins_temp, gen(binned)	
				local fitting_graph = "fpfit ldelta1p_s ldelta1s_s if rank1_s > 1 & ldelta1s_s > -.15 & ldelta1s_s < 0"
				local fitting_graph = "`fitting_graph' , estopts(deg(4) powers(0 1 2 3 4)) color(`lcolor') lwidth(thick)"
				if ustrregexm("`graphtableop'","local_linear"){
					rdplot ldelta1p_s ldelta1s_s if tie1s ~= 1 & rank1_s > 1, p(1) h( ) hide
					local fitting_graph = "function y = e(coef_l)[1,1] + e(coef_l)[2,1]*x, range(-.1 0) lc(`lcolor') lwidth(thick) lpattern(dash)"
				}
				else if ustrregexm("`graphtableop'", "nofit"){
					local fitting_graph = "function y = 0 , range(-.05 0) lc(gs5%100)"
				}
				twoway(scatter ldelta1p_s ldelta1s_s if binned == 1, ytitle("% Difference in Price", ///
					margin(-1 -2 0 0 ) /*orientation(horizontal)*/) ///
					xlabel(-.1(.05)0) /*ytitle("`tileft'", orientation(horizontal))*/ ///
					xtitle("% Difference in Score", margin(0 0 0 2)) ylabel(0(.05).1, angle(0)) color(`mcolor0') msize(`msz')) ///
					(`fitting_graph'), ///
						 name(`gname') legend(off) title("`gtitle'",) graphregion(c(white)) ///
							/*t1title("{it:{&beta}}(se):`est1s'(`se1s'); h = `h'", place(se) ring(0) size(small))*/ ///
							/*t2title("N=`e(N_l)'; {it:t} =`ts1s'", place(se) ring(0) size(small))*/ ///
						 xline(0,lpat("l") lcolor(black)) yline(0,lpat("l") lcolor(black)) ///
							xsc(r(-.105 .005)) ysc(r(-.02 .105)) xsize(4) ysize(4) graphregion(c(white))
				erase bins_temp.dta
				/*
				if ustrregexm("local_linear", "`graphtableop'"{
					cap graph drop u`days'_`runningvar'
					rdplot `outcomevar'`days' `runningvar' if abs(`runningvar') < $threshold_fg & ///
								`runningvar' ~= 0, p(1) h( ) ///
					graph_options(title("`days' Days", size(large)) name(u`days'_`runningvar') legend(off) ///
						xtitle({&Delta}) graphregion(color(white) lcolor(none)) ///
						/*t2title("From_`start_day'" "Thru_`end_day'", ///
							size(small) place(nw) ring(1))*/ ///
						subtitle("winners　　　　　losers", size(medium) ring(5) margin(zero)) ///
						t2title("{it:{&beta}}({it:se}):`tau'(`se_tau')`star10'", ///
							size(small) place(ne) ring(5) margin(zero)) ///
						ylabel(/*0(.2)1*/, angle(0) format(%3.1g)) /*ytitle(`outcomevar_label')*/ ///
						t1title("{it:h} = `hl'; {it:N} = `obs'", size(small) place(ne) margin(zero) height(.01) ring(5)))
				}
				*/
				
				
				
			*di "tau:`tau_s'"				
			}
			if ustrregexm("`ii'", "provide_table"){
				if ustrregexm("graphtableop","estpost_([^_]+)"){
					local estpost_exp = ustrregexs(1)
				} 
				*estpost sum sales_thousand profits_thou engineers ftt_ts1s ftt_ts1p if firm_treatment == 1& _merge == 3
				*est store treatment
			}
		}
	restore
	est restore rd
	return local tstat = `e(tau_bc_l)' / sqrt(Bl[1,1]) 
	return local se = sqrt(Bl[1,1]) 
	return local tau = `e(tau_bc_l)'
	return local est = `e(tau_bc_l)'
	return local N = `e(N_l)'
	return local h = `e(h_l)'
end




cap drop thebidder
cap program drop rddelta1x
program rddelta1x, rclass
	args ii st_fy en_fy gname gtitle msz st_mdybid ed_mdybid graphtableop bwselector color01
	preserve
		*cap drop thebidder
		sort thebidder ad_firm
		local firmNM = nm_firm[1]
		local firmRG = region[1]
		local firmAD = ad_firm[1]
		local firmID = firmID[1]
		if "`color01'" == "color"{
			local mcolor0 = "navy"
			local mcolor1 = "cyan"
			local lcolor = "orange"
			local graphregioncolor = ""
		}
		else{
			local mcolor0 = "gs5%80"
			local mcolor1 = "gs5%80"
			local lcolor = "gs10"
			local graphregioncolor = "white"
		}
		
		di as result "### `firmNM';id:`ii';`firmPR'`firmCT'; bhat=`est', t=`ts' ###"
		cap drop theauction
		qui bys id: egen theauction = max( thebidder == 1 )
		/*count if theauction == 1 & fy_con >= `st_fy' & fy_con <= `en_fy' */
		qui keep if (theauction == 1 | rank1_s == 1 ) & fy_con >= `st_fy' & fy_con <= `en_fy'  & FLAG == 0 /*used in survey*/
		qui keep if (theauction == 1 | rank1_s == 1 ) & MDYbid >= `st_mdybid' & MDYbid <= `ed_mdybid' & FLAG == 0 /*used in paper*/
		/* Do not include auctions in which (tie`z'`k' == 1) highest scores/prices are tie*/
		/* scoreが同率の1位と2位の者の価格bidは通常違うので、一位をどちらの業者にするかで2位以下の者すべての価格乖離率dep`z'sが変わり、RDの結果が変わるのを防ぐため
		なお、set seed 1では解決にならないのは、サンプルが変わって、行の番号が変わると同率の1位と2位の者のどちらをrank1_s = 1にするかは変化するから*/
		local leftright = "l"
		qui replace ldelta1p_s = -ldelta1s_s if rank1_s == 1
		*scatter ldelta1p_s ldelta1s_s
		
		qui count
		*di "cccccc td(`st_mdybid') td(`ed_mdybid') `r(N)' cccccc"
		local success = 0
		local drop = 0
		while `success' == 0 {				
		    qui sum ldelta1s_s if tie1s ~= 1 & (ldelta1s_s < 0 |  ldelta1s_s > `drop')
			cap noisily rdbwselect2a ldelta1p_s ldelta1s_s `leftright' ///
				if tie1s ~= 1 & (ldelta1s_s < 0 | ldelta1s_s >= `drop'), kernel(tri) vce(cluster id) bwselect(`bwselector')
			cap noisily rdrobust ldelta1p_s ldelta1s_s if tie1s ~= 1 , vce(cluster id) kernel(tri) 	///
						h(`e(h_`bwselector'_l)' `e(h_`bwselector'_r)') b(`e(b_`bwselector'_l)' `e(b_`bwselector'_r)') 
			if _rc == 0 {
				local success = 1
				di "dropping samples to the right of zero"
				*continue, break
			}
			else if `drop' > 0.01{
				di "### drop if d(`runningvar', 0) < `drop' for rank1 bidder ###"
				local success = 1
				*continue, break	
			}
			else{
				local drop = `drop' + .001
			}
		}
		if `success' == 1 {
			local est1s = string(`e(tau_bc_l)', "%6.3f" )
			mat Bl = e(V_rb_l)
			mat Br = e(V_rb_r)
			local se1s = string(sqrt(Bl[1,1]), "%6.3f" )
			local ts1s = string(`e(tau_bc_l)' / sqrt(Bl[1,1]) , "%6.3f" )
			local h = string(`e(h_l)' , "%6.3f" )
			di "**** est:" `e(tau_bc)'
			di "**** est_l:" `e(tau_bc_l)'
			di "**** est_r:" `e(tau_bc_r)'
			di "**** se_l:" sqrt(Bl[1,1])
			di "**** se_r:" sqrt(Br[1,1])
			di "**** tstat:" `ts1s'
			di "#### N:" `e(N_l)'

			cap graph drop `gname'
			if "`ii'" != "nograph" {
				/* x軸評価点を得るためのlpoly*/
				cap drop xvar
				cap drop yvar
				*di"abc"
				local onebw = `e(h_l)'
				local bw_lpoly = ""
				if ustrregexm("`graphtableop'","onebw"){
					local bw_lpoly = "bw(`onebw')"
					di "**** `graphtableop' *****"
				}
				lpoly ldelta1p_s ldelta1s_s if rank1_s > 1 & ldelta1s_s > -.15 & ldelta1s_s < 0 ///
					& abs(ldelta1p_s -.05) < .13, deg(1) `bw_lpoly' kernel(tri) gen(xvar yvar) nograph
				*di"hij"
				sort xvar
				*count if xvar < . /*かならず50になる（lpolyのデフォルトの評価点数は50だから*/
				qui replace xvar = 0 if _n == 50 + 1
				qui drop yvar
				/* 0を含むx軸上の50+1個の評価点における推定値を得るためのlpoly (推定値はyvarに格納)*/
				lpoly ldelta1p_s ldelta1s_s if rank1_s > 1 & ldelta1s_s > -.15 & ldelta1s_s < 0 & tie1s ~= 1 ///
					& abs(ldelta1p_s -.05) < .13, gen(yvar) at(xvar) `bw_lpoly' kernel(tri) deg(1) nograph
				qui sum yvar if xvar == 0, mean /* 切片*/
				local tau_s = r(mean)
				twoway(scatter ldelta1p_s ldelta1s_s if ldelta1p_s > 0 & abs(ldelta1s_s) < .15 & tie1s ~= 1 ///
					& abs(ldelta1p_s - .05) < .13 & rank1_s > 1 & tie1s ~= 1, ytitle("% Difference in Price", ///
					margin(-1 -2 0 0 ) /*orientation(horizontal)*/ ) ///
					xlabel(-.15(.05)0) /*ytitle("`tileft'", orientation(horizontal))*/ ///
					xtitle("% Difference in Score", margin(0 0 0 2)) ylabel(-.05(.05).15, angle(0)) color(`mcolor0') msize(`msz')) ///
					(scatter ldelta1p_s ldelta1s_s if ldelta1p_s <= 0 & abs(ldelta1s_s) < .15 & tie1s ~= 1 ///
						& abs(ldelta1p_s - .05) < .13 & rank1_s > 1, color(`mcolor1') msize(`msz')) ///
						/*(lpolyci ldelta1p_s ldelta1s_s, clc(orange) alw(medthick) deg(1) ///
							clw(medthick) fc(none) alp(shortdash) alc(gs5) xlabel(-.15(.05)0) kernel(tri) )*/ ///
					(line yvar xvar if abs(yvar-.05)<.13 & abs(xvar) <.15 & tie1s~=1, sort color(`lcolor') lwidth(thick)) /// 
						, name(`gname') legend(off) title("`gtitle'",) /*graphregion(c(white))*/ ///
							/*t1title("{it:{&beta}}(se):`est1s'(`se1s'); h = `h'", place(se) ring(0) size(small))*/ ///
							/*t2title("N=`e(N_l)'; {it:t} =`ts1s'", place(se) ring(0) size(small))*/ ///
						 xline(0,lpat("l") lcolor(black)) yline(0,lpat("l") lcolor(black)) ///
							xsc(r(-.16 .02)) ysc(r(-.08 .18)) xsize(4) ysize(4) graphregion(c(`graphregioncolor'))
				if _rc == 0 {
					*qui graph export "Graph\firmtest2017/T`order'_`firmNM'Rg`firmRG'(`firmPR'`firmCT';`firmID').png", width(2048) replace
				}
			*di "tau:`tau_s'"
			}
			if ustrregexm("`ii'", "provide_table"){
				if ustrregexm("graphtableop","estpost_([^_]+)"){
					local estpost_exp = ustrregexs(1)
				} 
				*estpost sum sales_thousand profits_thou engineers ftt_ts1s ftt_ts1p if firm_treatment == 1& _merge == 3
				*est store treatment
			}
		}
	restore
	return local tstat = `e(tau_bc_l)' / sqrt(Bl[1,1]) 
	return local se = sqrt(Bl[1,1]) 
	return local tau = `e(tau_bc_l)'
	return local est = `e(tau_bc_l)'
	return local N = `e(N_l)'
	return local h = `e(h_l)'
end


cap drop thebidder
cap program drop rddelta1xgp
program rddelta1xgp, rclass
	args ii st_fy en_fy gname gtitle msz st_mdybid ed_mdybid graphtableop bwselector
	preserve
		pause on
		*cap drop thebidder
		sort thebidder ad_firm
		local firmNM = nm_firm[1]
		local firmRG = region[1]
		local firmAD = ad_firm[1]
		local firmID = firmID[1]
		
		di as result "### `firmNM';id:`ii';`firmPR'`firmCT'; bhat=`est', t=`ts' ###"
		cap drop theauction
		qui bys id: egen theauction = max( thebidder == 1 )
		/*count if theauction == 1 & fy_con >= `st_fy' & fy_con <= `en_fy' */
		qui keep if (theauction == 1 | rank1_s == 1 ) & fy_con >= `st_fy' & fy_con <= `en_fy'  & FLAG == 0 /*used in survey*/
		qui keep if (theauction == 1 | rank1_s == 1 ) & MDYbid >= `st_mdybid' & MDYbid <= `ed_mdybid' & FLAG == 0 /* used in paper*/
		/* Do not include auctions in which (tie`z'`k' == 1) highest scores/prices are tie*/
		/* scoreが同率の1位と2位の者の価格bidは通常違うので、一位をどちらの業者にするかで2位以下の者すべての価格乖離率dep`z'sが変わり、RDの結果が変わるのを防ぐため
		なお、set seed 1では解決にならないのは、サンプルが変わって、行の番号が変わると同率の1位と2位の者のどちらをrank1_s = 1にするかは変化するから*/
		local leftright = "l"
		qui replace ldelta1p_s = -ldelta1s_s if rank1_s == 1
		*scatter ldelta1p_s ldelta1s_s
		
		qui count
		*di "cccccc td(`st_mdybid') td(`ed_mdybid') `r(N)' cccccc"
		local success = 0
		local drop = 0
		while `success' == 0 {				
		    qui sum ldelta1s_s if tie1s ~= 1 & (ldelta1s_s < 0 |  ldelta1s_s > `drop')
			cap noisily rdbwselect2a ldelta1p_s ldelta1s_s `leftright' if tie1s ~= 1  ///
				& (ldelta1s_s < 0 | ldelta1s_s > `drop'), kernel(tri) vce(cluster id) bwselect(`bwselector')
			cap noisily rdrobust ldelta1p_s ldelta1s_s if tie1s ~= 1 , vce(cluster id) kernel(tri) 	///
						h(`e(h_`bwselector'_l)' `e(h_`bwselector'_r)') b(`e(b_`bwselector'_l)' `e(b_`bwselector'_r)') 
			if _rc == 0 {
				local success = 1
				di "dropping samples to the right of zero"
				*continue, break
			}
			else if `drop' > 0.01{
				di "### drop if d(`runningvar', 0) < `drop' for rank1 bidder ###"
				local success = 1
				*continue, break	
			}
			else{
				local drop = `drop' + .001
			}
		}
		if `success' == 1 {
			local est1s = string(`e(tau_bc_l)', "%6.3f" )
			mat Bl = e(V_rb_l)
			mat Br = e(V_rb_r)
			local se1s = string(sqrt(Bl[1,1]), "%6.3f" )
			local ts1s = string(`e(tau_bc_l)' / sqrt(Bl[1,1]) , "%6.3f" )
			local h = string(`e(h_l)' , "%6.3f" )
			di "**** est:" `e(tau_bc)'
			di "**** est_l:" `e(tau_bc_l)'
			di "**** est_r:" `e(tau_bc_r)'
			di "**** se_l:" sqrt(Bl[1,1])
			di "**** se_r:" sqrt(Br[1,1])
			di "**** tstat:" `ts1s'
			di "#### N:" `e(N_l)'

			cap graph drop `gname'
			if "`ii'" != "nograph" {
				/* x軸評価点を得るためのlpoly*/
				cap drop xvar
				cap drop yvar
				*di"abc"
				local onebw = `e(h_l)'
				local bw_lpoly = ""
				if ustrregexm("`graphtableop'","onebw"){
					local bw_lpoly = "bw(`onebw')"
					di "**** `graphtableop' *****"
				}
				
				/*di"hij"
				sort xvar
				*count if xvar < . /*かならず50になる（lpolyのデフォルトの評価点数は50だから*/
				qui replace xvar = 0 if _n == 50 + 1
				qui drop yvar
				/* 0を含むx軸上の50+1個の評価点における推定値を得るためのlpoly (推定値はyvarに格納)*/
				lpoly ldelta1p_s ldelta1s_s if rank1_s > 1 & ldelta1s_s > -.15 & ldelta1s_s < 0 & tie1s ~= 1 ///
					& abs(ldelta1p_s -.05) < .13, gen(yvar) at(xvar) `bw_lpoly' kernel(tri) deg(1) nograph
				*/
				*qui sum yvar if xvar == 0, mean /* 切片*/
				*local tau_s = r(mean)
				twoway(scatter ldelta1p_s ldelta1s_s if ldelta1p_s > 0 & abs(ldelta1s_s) <= .15 & tie1s ~= 1 ///
					& abs(ldelta1p_s - .05) < .13 & rank1_s > 1 & tie1s ~= 1, ytitle("% Difference in Price", ///
					margin(-1 -2 0 0 ) /*orientation(horizontal)*/ ) ///
					xlabel(-.15(.05)0) /*ytitle("`tileft'", orientation(horizontal))*/ ///
					xtitle("% Difference in Score", margin(0 0 0 2)) ylabel(-.05(.05).15, angle(0)) color(gs5%80) msize(`msz')) ///
					(scatter ldelta1p_s ldelta1s_s if ldelta1p_s <= 0 & abs(ldelta1s_s) < .15 & tie1s ~= 1 ///
						& abs(ldelta1p_s - .05) < .13 & rank1_s > 1, color(gs5%80) msize(`msz')) ///
						/*(lpolyci ldelta1p_s ldelta1s_s, clc(orange) alw(medthick) deg(1) ///
							clw(medthick) fc(none) alp(shortdash) alc(gs5) xlabel(-.15(.05)0) kernel(tri) )*/ ///
					(fpfit ldelta1p_s ldelta1s_s if rank1_s > 1 & ldelta1s_s > -.15 & ldelta1s_s < 0 ///
					& abs(ldelta1p_s -.05) < .13, estopts(deg(4) powers(0 1 2 3 4)) color(gs10) lwidth(thick)) ///
					/*(line yvar xvar if abs(yvar-.05)<.13 & abs(xvar) <.15 & tie1s~=1, sort color(gs10) lwidth(thick))*/ /// 
						, name(`gname') legend(off) title("`gtitle'",) graphregion(c(white)) ///
							/*t1title("{it:{&beta}}(se):`est1s'(`se1s'); h = `h'", place(se) ring(0) size(small))*/ ///
							/*t2title("N=`e(N_l)'; {it:t} =`ts1s'", place(se) ring(0) size(small))*/ ///
						 xline(0,lpat("l") lcolor(black)) yline(0,lpat("l") lcolor(black)) ///
							xsc(r(-.16 .02)) ysc(r(-.08 .18)) xsize(4) ysize(4) graphregion(c(white))
				if _rc == 0 {
					*qui graph export "graph/firmtest2017/T`order'_`firmNM'Rg`firmRG'(`firmPR'`firmCT';`firmID').png", width(2048) replace
				}
			*di "tau:`tau_s'"
			}

			if ustrregexm("`ii'", "provide_table"){
				if ustrregexm("`graphtableop'","estpost_([^_]+)"){
					local estpost_exp = ustrregexs(1)
				}
				if ustrregexm("`graphtableop'","replace"){
					local replace = "replace"
				}
				outreg2 using "../temp/deltas_scatter_polinomial.tex", `replace'  ///
				tex(fragment) nonote noobs ///
				addstat(RD Robust Est., e(tau_bc_l), Robust SE, `se1s', t-Stat, `ts1s', ///
				Observations, e(N_l), Bandwidth, e(h_l), Order polyn., e(p))
				*estpost sum sales_thousand profits_thou engineers ftt_ts1s ftt_ts1p if firm_treatment == 1& _merge == 3
				*est store treatment
			}
		}
	restore
	return local tstat = `e(tau_bc_l)' / sqrt(Bl[1,1]) 
	return local se = sqrt(Bl[1,1]) 
	return local tau = `e(tau_bc_l)'
	return local est = `e(tau_bc_l)'
	return local N = `e(N_l)'
	return local h = `e(h_l)'
end




cap program drop rddelta1x_binscatter_p
program rddelta1x_binscatter_p, rclass
	args id st_fy en_fy gname gtitle msz st_mdybid ed_mdybid graphtableop bwselector color01 nquantiles

	args ii st_fy en_fy gname gtitle msz st_mdybid ed_mdybid graphtableop bwselector
	preserve
		sort thebidder ad_firm
		local firmNM = nm_firm[1]
		local firmRG = region[1]
		local firmAD = ad_firm[1]
		local firmID = firmID[1]
		if "`color01'" == "color"{
			local mcolor0 = "navy"
			local mcolor1 = "cyan"
			local lcolor = "orange"
			local graphregioncolor = ""
		}
		else{
			local mcolor0 = "gs5%80"
			local mcolor1 = "gs5%80"
			local lcolor = "gs10%75"
			local graphregioncolor = "white"
		}
		di as result "### `firmNM';id:`ii';`firmPR'`firmCT'; bhat=`est', t=`ts' ###"
		cap drop theauction
		qui bys id: egen theauction = max( thebidder == 1 )
		*qui keep if (theauction == 1 | rank1_p == 1 ) & fy_con >= `st_fy' & fy_con <= `en_fy'  & FLAG == 0 /*used in survey*/
		qui keep if (theauction == 1 | rank1_p == 1 ) & MDYbid >= `st_mdybid' & MDYbid <= `ed_mdybid' & FLAG == 0 /*used in paper*/
		/**** qui keep if flag != 1 *****/
		
		local leftright = "r"
		qui replace ldelta1s_p = -ldelta1p_p if rank1_p == 1
		*scatter ldelta1s_p ldelta1p_p
		*rdplot ldelta1s_p ldelta1p_p if tie1p~=1
		*sum ldelta1s_p ldelta1p_p if tie1p~=1, d
		cap drop rdplot_*
		cap graph drop `gname'
		
		local success = 0
		local drop = 0
		while `success' == 0 {
			cap{
			    noisily sum ldelta1p_p if tie1p~=1 & (`drop' > ldelta1p_p | ldelta1p_p>0) & ldelta1p_p<0
			    noisily rdbwselect2a ldelta1s_p ldelta1p_p `leftright' if tie1p~=1 /*2a is created on 24Aug23*/ ///
				 &(`drop' > ldelta1p_p | ldelta1p_p>0) /*abs(ldelta1s_p)<.18*/, ///
				kernel(tri) vce(cluster id) bwselect(`bwselector')
				noisily rdrobust ldelta1s_p ldelta1p_p if tie1p ~= 1 ///
				, vce(cluster id) kernel(tri) ///
						h(`e(h_`bwselector'_l)' `e(h_`bwselector'_r)') b(`e(b_`bwselector'_l)' `e(b_`bwselector'_r)')
			}
			if _rc == 0 {
				local success = 1
				continue, break
			}
			else if `drop' < - 0.01{
				local success = 1
				di "### drop if d(`runningvar', 0) < `drop' for rank1 bidder ###"
			}
			else{
				di as error "drop left obs close to zero"
				local drop = `drop' - .001
				sleep 100
			}
		}
		if `success' == 1{
			local est1p = string(`e(tau_bc_r)', "%6.3f" )
			mat Br = e(V_rb_r)
			local se1p = string(sqrt(Br[1,1]), "%6.3f" )
			local ts1p = string(`e(tau_bc_r)' / sqrt(Br[1,1]) , "%6.3f" )
			local h = string(`e(h_r)', "%6.3f" )
			di "**** est:" `e(tau_bc)'
			di "**** est_l:" `e(tau_bc_l)'
			di "**** est_r:" `e(tau_bc_r)'
			di "**** se_r:" sqrt(Br[1,1])	
			di "***   h_r" `e(h_r)'
			di "**** se_r:" sqrt(Br[1,1])
			di "**** tstat:" `ts1p'
			di "#### N:" `e(N_l)'
			eststo rd

			if "`ii'" != "nograph" {	
				qui binscatter ldelta1s_p ldelta1p_p if rank1_p > 1 & ldelta1p_p < .1 & ldelta1p_p > 0 & tie1p ~= 1 ///
					, line(none) savedata(bins_temp) replace nquantiles(`nquantiles')
				tempfile __temp
				sleep 500
				*pause
				save `__temp', replace
				import delimited using bins_temp.csv, varnames(1) delimiters(",") clear
				erase "bins_temp.do"
				erase bins_temp.csv
				save bins_temp, replace
				sleep 500
				use `__temp', clear
				append using bins_temp, gen(binned)	
				
		
				local fitting_graph = "fpfit ldelta1s_p ldelta1p_p if rank1_p > 1 & ldelta1p_p < .15 & ldelta1p_p > 0 & tie1p ~= 1"
				local fitting_graph = "`fitting_graph' & abs(ldelta1s_p + .05 ) < .13, estopts(deg(4) powers(0 1 2 3 4)) color(`lcolor') lwidth(thick)"
				if ustrregexm("`graphtableop'","local_linear"){
					rdplot ldelta1s_p ldelta1p_p if tie1p ~= 1, p(1) h( )
					local fitting_graph = "function y = e(coef_r)[1,1] + e(coef_r)[2,1]*x, range(0 .15) lc(`lcolor') lwidth(thick) lpattern(dash)"
					pause
				}		
				else if ustrregexm("`graphtableop'", "nofit"){
					local fitting_graph = "function y = 0 , range(0 .01) lc(gs5%100)"
				}
				twoway(scatter ldelta1s_p ldelta1p_p if binned == 1, ylabel(-.20(.05)0, angle(0) format(%5.2g))  ///
					xlabel(0(.05).1) /*ytitle("`tileft'", orientation(horizontal))*/ ///
					xtitle("% Difference in Price", margin(0 0 0 2)) ytitle("% Difference in Score", margin(-1 -3 0 0) ///
						/*orientation(horizontal)*/) color(`mcolor0') msize(`msz')) ///
					(`fitting_graph'), ///
						name(`gname') legend(off) title("`gtitle'",) graphregion(c(white)) ///
							/*subtitle("tau:`tau_p'" , place(se) ring(0))*/ ///
							/*subtitle("{it:t}=`ts1p'" , place(se) ring(0))*/  ///
							/*t1title("{it:{&beta}}(se):`est1p'(`se1p')", place(ne) ring(0) size(small))*/ ///
							/*t2title("N=`e(N_r)'; {it:t} =`ts1p'; h=`h'", place(ne) ring(0) size(small))*/ ///
						xline(0,lpat("l") lcolor(black)) yline(0,lpat("l") lcolor(black)) ///
							xsc(r(-.005 .105 )) ysc(r(-.22 .02)) xsize(4) ysize(4) plotregion(margin(tiny))

				erase bins_temp.dta
			}
		}
		/*scatter depvar indepvar if abs(depvar) < .2 & abs(indepvar) < .2 */
		di "tau:`tau_p'"							
		*save ddd, replace
	restore
	est restore rd
	return local tstat = `e(tau_bc_r)' / sqrt(Br[1,1])
	return local se = sqrt(Br[1,1])
	return local tau = `est1p'
	return local est = `e(tau_bc_r)'
	return local N = `e(N_r)'
	return local h = `e(h_r)'
end


/* For nippo*/
cap program drop rddelta1p
program rddelta1p, rclass
	args ii st_fy en_fy gname gtitle msz st_mdybid ed_mdybid graphtableop bwselector color01
	preserve
		sort thebidder ad_firm
		local firmNM = nm_firm[1]
		local firmRG = region[1]
		local firmAD = ad_firm[1]
		local firmID = firmID[1]
		if "`color01'" == "color"{
			local mcolor0 = "green"
			local mcolor1 = "lime"
			local lcolor = "maroon"
			local graphregioncolor = ""
		}
		else{
			local mcolor0 = "gs5%80"
			local mcolor1 = "gs5%80"
			local lcolor = "gs10"
			local graphregioncolor = "white"
		}
		
		di as result "### `firmNM';id:`ii';`firmPR'`firmCT'; bhat=`est', t=`ts' ###"
		cap drop theauction
		qui bys id: egen theauction = max( thebidder == 1 )
		qui keep if (theauction == 1 | rank1_p == 1 ) & fy_con >= `st_fy' & fy_con <= `en_fy'  & FLAG == 0 /*used in survey*/
		*qui keep if (theauction == 1 | rank1_p == 1 ) & MDYbid >= `st_mdybid' & MDYbid <= `ed_mdybid' & FLAG == 0 /*used in paper*/
		/**** qui keep if flag != 1 *****/
		
		local leftright = "r"
		qui replace ldelta1s_p = -ldelta1p_p if rank1_p == 1
		*scatter ldelta1s_p ldelta1p_p
		*rdplot ldelta1s_p ldelta1p_p if tie1p~=1
		*sum ldelta1s_p ldelta1p_p if tie1p~=1, d
		cap drop rdplot_*
		cap graph drop `gname'
		
		local success = 0
		local drop = 0
		while `success' == 0 {
			*
			cap{
			    *noisily sum ldelta1p_p if tie1p~=1 & (`drop' >= ldelta1p_p | ldelta1p_p>0) & ldelta1p_p<0
			    noisily rdbwselect2a ldelta1s_p ldelta1p_p `leftright' if tie1p~=1 /*2a is created on 24Aug23*/ ///
				&(`drop' > ldelta1p_p | ldelta1p_p>0) /*abs(ldelta1s_p)<.18*/, ///
				kernel(tri) vce(cluster id) bwselect(`bwselector')
				noisily rdrobust ldelta1s_p ldelta1p_p if tie1p ~= 1 ///
				, vce(cluster id) kernel(tri) ///
						h(`e(h_`bwselector'_l)' `e(h_`bwselector'_r)') b(`e(b_`bwselector'_l)' `e(b_`bwselector'_r)')
			}
			if _rc == 0 {
				local success = 1
				continue, break
			}
			else if `drop' < - 0.01{
				local success = 1
				di "### drop if d(`runningvar', 0) < `drop' for rank1 bidder ###"
			}
			else{
				di as error "drop left obs close to zero"
				local drop = `drop' - .001
				sleep 100
			}
		}
		if `success' == 1{
			local est1p = string(`e(tau_bc_r)', "%6.3f" )
			mat Br = e(V_rb_r)
			local se1p = string(sqrt(Br[1,1]), "%6.3f" )
			local ts1p = string(`e(tau_bc_r)' / sqrt(Br[1,1]) , "%6.3f" )
			local h = string(`e(h_r)', "%6.3f" )
			di "**** est:" `e(tau_bc)'
			di "**** est_l:" `e(tau_bc_l)'
			di "**** est_r:" `e(tau_bc_r)'
			di "**** se_r:" sqrt(Br[1,1])	
			di "***   h_r" `e(h_r)'
			if "`ii'" != "nograph" {
				/* x軸評価点を得るためのlpoly*/
				cap drop xvar
				cap drop yvar
				local onebw = `e(h_r)'
				local bw_lpoly = ""
				if ustrregexm("`graphtableop'","onebw"){
					local bw_lpoly = "bw(`onebw')"
				}
				
				lpoly ldelta1s_p ldelta1p_p if rank1_p > 1 & ldelta1p_p < .15 & ldelta1p_p > 0 & tie1p ~= 1 ///
					& abs(ldelta1s_p + .05 ) < .13, deg(1) `bw_lpoly' kernel(tri) gen(xvar yvar) nograph
				sort xvar
				*count if xvar < . /*かならず50になる（lpolyのデフォルトの評価点数は50だから*/
				qui replace xvar = 0 if _n == 50 + 1
				qui drop yvar
				/* 推定値を得るためのlpoly (推定値はyvarに格納)*/
				lpoly ldelta1s_p ldelta1p_p if rank1_p > 1 & ldelta1p_p < .15 & ldelta1p_p >= 0 & tie1p ~= 1 ///
					& abs(ldelta1s_p + .05 ) < .13, gen(yvar) at(xvar) `bw_lpoly' kernel(tri) deg(1) nograph
				/* to get intersept*/
				qui sum yvar if xvar == 0, mean /* 切片*/
				local tau_p = r(mean)
				
				twoway(scatter ldelta1s_p ldelta1p_p if ldelta1s_p > 0 & abs(ldelta1p_p) < .15 ///
					& abs(ldelta1s_p + .05) < .13 & rank1_p > 1 & tie1p ~= 1, ///
					xlabel(0(.05).15) /*ytitle("`tileft'", orientation(horizontal))*/ ///
					xtitle("% Difference in Price", margin(0 0 0 2)) ytitle("% Difference in Score", margin(-1 -3 0 0) ///
						/*orientation(horizontal)*/) color(`mcolor1') msize(`msz')) ///
					(scatter ldelta1s_p ldelta1p_p if ldelta1s_p <= 0 & abs(ldelta1p_p) < .15 & tie1p ~= 1 ///
						& abs(ldelta1s_p + .05) < .13 & rank1_p > 1 , ///
						ylabel(-.15(.05).05, angle(0) format(%5.2g)) color(`mcolor0') msize(`msz')) ///
					(line yvar xvar if abs(yvar+.05)<.13 & abs(xvar)<.15&tie1p ~= 1,sort color(`lcolor') lwidth(thick)), /// 
						name(`gname') legend(off) title("`gtitle'", /*size(medsmall)*/) ///
							/*subtitle("tau:`tau_p'" , place(se) ring(0))*/ ///
							/*subtitle("{it:t}=`ts1p'" , place(se) ring(0))*/ graphregion(c(`graphregioncolor')) ///
							/*t1title("{it:{&beta}}(se):`est1p'(`se1p')", place(ne) ring(0) size(small))*/ ///
							/*t2title("N=`e(N_r)'; {it:t} =`ts1p'; h=`h'", place(ne) ring(0) size(small))*/ ///
							xline(0,lpat("l") lcolor(black)) yline(0,lpat("l") lcolor(black)) ///
							xsc(r(-.02 .16 )) ysc(r(-.18 .08)) xsize(4) ysize(4) plotregion(margin(tiny))
			}
		}
		/*scatter depvar indepvar if abs(depvar) < .2 & abs(indepvar) < .2 */
		di "tau:`tau_p'"							
		*save ddd, replace
	restore
	return local tstat = `e(tau_bc_r)' / sqrt(Br[1,1])
	return local se = sqrt(Br[1,1])
	return local tau = `est1p'
	return local est = `e(tau_bc_r)'
	return local N = `e(N_r)'
	return local h = `e(h_r)'
end



cap program drop rddelta1pgp
program rddelta1pgp, rclass
	args ii st_fy en_fy gname gtitle msz st_mdybid ed_mdybid graphtableop bwselector
	preserve
		sort thebidder ad_firm
		local firmNM = nm_firm[1]
		local firmRG = region[1]
		local firmAD = ad_firm[1]
		local firmID = firmID[1]
		
		di as result "### `firmNM';id:`ii';`firmPR'`firmCT'; bhat=`est', t=`ts' ###"
		cap drop theauction
		qui bys id: egen theauction = max( thebidder == 1 )
		*qui keep if (theauction == 1 | rank1_p == 1 ) & fy_con >= `st_fy' & fy_con <= `en_fy'  & FLAG == 0 /*used in survey*/
		qui keep if (theauction == 1 | rank1_p == 1 ) & MDYbid >= `st_mdybid' & MDYbid <= `ed_mdybid' & FLAG == 0 /*used in paper*/
		/**** qui keep if flag != 1 *****/
		
		local leftright = "r"
		qui replace ldelta1s_p = -ldelta1p_p if rank1_p == 1
		*scatter ldelta1s_p ldelta1p_p
		*rdplot ldelta1s_p ldelta1p_p if tie1p~=1
		*sum ldelta1s_p ldelta1p_p if tie1p~=1, d
		cap drop rdplot_*
		cap graph drop `gname'
		
		local success = 0
		local drop = 0
		while `success' == 0 {
			*
			cap{
			    noisily sum ldelta1p_p if tie1p~=1 & (`drop' > ldelta1p_p | ldelta1p_p>0) & ldelta1p_p<0
			    noisily rdbwselect2a ldelta1s_p ldelta1p_p `leftright' if tie1p~=1 /*2a is created on 24Aug23*/ ///
				 &(`drop' > ldelta1p_p | ldelta1p_p>0) /*abs(ldelta1s_p)<.18*/, ///
				kernel(tri) vce(cluster id) bwselect(`bwselector')
				noisily rdrobust ldelta1s_p ldelta1p_p if tie1p ~= 1 ///
				, vce(cluster id) kernel(tri) ///
						h(`e(h_`bwselector'_l)' `e(h_`bwselector'_r)') b(`e(b_`bwselector'_l)' `e(b_`bwselector'_r)')
			}
			if _rc == 0 {
				local success = 1
				continue, break
			}
			else if `drop' < - 0.01{
				local success = 1
				di "### drop if d(`runningvar', 0) < `drop' for rank1 bidder ###"
			}
			else{
				di as error "drop left obs close to zero"
				local drop = `drop' - .001
				sleep 100
			}
		}
		if `success' == 1{
			local est1p = string(`e(tau_bc_r)', "%6.3f" )
			mat Br = e(V_rb_r)
			local se1p = string(sqrt(Br[1,1]), "%6.3f" )
			local ts1p = string(`e(tau_bc_r)' / sqrt(Br[1,1]) , "%6.3f" )
			local h = string(`e(h_r)', "%6.3f" )
			di "**** est:" `e(tau_bc)'
			di "**** est_l:" `e(tau_bc_l)'
			di "**** est_r:" `e(tau_bc_r)'
			di "**** se_r:" sqrt(Br[1,1])	
			di "***   h_r" `e(h_r)'
			if "`ii'" != "nograph" {
				/* x軸評価点を得るためのlpoly*/
				cap drop xvar
				cap drop yvar
				local onebw = `e(h_r)'
				local bw_lpoly = ""
				if ustrregexm("`graphtableop'","onebw"){
					local bw_lpoly = "bw(`onebw')"
				}
				twoway(scatter ldelta1s_p ldelta1p_p if ldelta1s_p > 0 & abs(ldelta1p_p) < .15 ///
					& abs(ldelta1s_p + .05) < .13 & rank1_p > 1 & tie1p ~= 1, ///
					xlabel(0(.05).15) /*ytitle("`tileft'", orientation(horizontal))*/ ///
					xtitle("% Difference in Price", margin(0 0 0 2)) ytitle("% Difference in Score", margin(-1 -3 0 0) ///
						/*orientation(horizontal)*/) color(gs5%80) msize(`msz')) ///
					(scatter ldelta1s_p ldelta1p_p if ldelta1s_p <= 0 & abs(ldelta1p_p) < .15 & tie1p ~= 1 ///
						& abs(ldelta1s_p + .05) < .13 & rank1_p > 1 , ///
						ylabel(-.15(.05).05, angle(0) format(%5.2g)) color(gs5%80) msize(`msz')) ///
					(fpfit ldelta1s_p ldelta1p_p if rank1_p > 1 & ldelta1p_p < .15 & ldelta1p_p > 0 & tie1p ~= 1 ///
					& abs(ldelta1s_p + .05) < .13, estopts(deg(4) powers(0 1 2 3 4)) color(gs10) lwidth(thick))  ///
					/*(line yvar xvar if abs(yvar+.05)<.13 & abs(xvar)<.15&tie1p ~= 1,sort color(gs10) lwidth(thick))*/, /// 
						name(`gname') legend(off) title("`gtitle'", /*size(medsmall)*/) ///
							/*subtitle("tau:`tau_p'" , place(se) ring(0))*/ ///
							/*subtitle("{it:t}=`ts1p'" , place(se) ring(0))*/  graphregion(c(white)) ///
							/*t1title("{it:{&beta}}(se):`est1p'(`se1p')", place(ne) ring(0) size(small))*/ ///
							/*t2title("N=`e(N_r)'; {it:t} =`ts1p'; h=`h'", place(ne) ring(0) size(small))*/ ///
							xline(0,lpat("l") lcolor(black)) yline(0,lpat("l") lcolor(black)) ///
							xsc(r(-.02 .16 )) ysc(r(-.18 .08)) xsize(4) ysize(4) plotregion(margin(tiny))
			}
		}
		if ustrregexm("`ii'", "provide_table"){
			if ustrregexm("`graphtableop'","replace"){
				local replace = "replace"
			}
			outreg2 using "../temp/deltap_scatter_polinomial.tex", `replace'  ///
			tex(fragment) nonote noobs ///
			addstat(RD Robust Est., e(tau_bc_r), Robust SE, `se1p', t-Stat, `ts1p', ///
			Observations, e(N_r), Bandwidth, e(h_r), Order polyn., e(p))
		}
		/*scatter depvar indepvar if abs(depvar) < .2 & abs(indepvar) < .2 */
		di "tau:`tau_p'"							
		*save ddd, replace
	restore
	return local tstat = `e(tau_bc_r)' / sqrt(Br[1,1])
	return local se = sqrt(Br[1,1])
	return local tau = `est1p'
	return local est = `e(tau_bc_r)'
	return local N = `e(N_r)'
	return local h = `e(h_r)'
end





/*
cap program drop npdelta1
program npdelta1, rclass
	args ii st_fy en_fy gname gtitle msz st_mdybid ed_mdybid graphtableop sp
	preserve
		sort thebidder ad_firm
		local firmNM = nm_firm[1]
		local firmRG = region[1]
		local firmAD = ad_firm[1]
		local firmID = firmID[1]
		local runvar = "ldelta1p_p"
		local outcomevar = "ldelta1s_p"
		local additional_condition = "& ldelta1p_p > 0 & ldelta1p_p < ."
		local runvar_label = "Price"
		local outcomevar_label = "Score"
		local scatter_ylabel = "-.15(.05).05"
		local scatter_xlabel = "0(.05).15"
		local scatter_xsc = "r(-.02 .16)"
		local scatter_ysc = "r(-.18 .08)"
		local scatter_outcomevar_offset = .05
		if "`sp'" == "s"{
			local runvar = "ldelta1s_s"
			local outcomevar = "ldelta1p_s"
			local additional_condition = "& ldelta1s_s < 0"
			local runvar_label = "Score"
			local outcomevar_label = "Price"
			local scatter_ylabel = "-.05(.05).15"
			local scatter_xlabel = "-.15(.05)0"
			local scatter_xsc = "r(-.16 .02)"
			local scatter_ysc = "r(-.08 .18)"
			local scatter_outcomevar_offset = -.05
		}
		
		di as result "### price/score: `sp'; `firmNM';id:`ii';`firmPR'`firmCT'; bhat=`est', t=`ts' ###"
		cap drop theauction
		qui bys id: egen theauction = max( thebidder == 1 )
		*qui keep if (theauction == 1 ) & fy_con >= `st_fy' & fy_con <= `en_fy'  & FLAG == 0
		qui keep if (theauction == 1 ) & MDYbid >= `st_mdybid' & MDYbid <= `ed_mdybid' ///
			& FLAG == 0 & tie1`sp' ~= 1 `additional_condition' 
		/*di "(theauction == 1 ) & MDYbid >= `st_mdybid' & MDYbid <= `ed_mdybid' & FLAG == 0 & tie1`sp' ~= 1 `additional_condition'"
		di "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
		count 
		di "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"*/
			
		/**** qui keep if flag != 1 *****/
		*rdplot ldelta1s_p ldelta1p_p if tie1p~=1
		cap drop rdplot_*
		cap graph drop `gname'
		
		local condition_plus = ""
		local success = 0
		local drop = 0
		local est = .
		local tstat = .
		local se = .
		local N = .
		local h = .
		nprobust_mse2 `outcomevar' `runvar' 
			
		if `r(success)' == 1{
			local est_st = string(`r(est)', "%6.3f" )
			local tstat_st = string(`r(tstat)', "%6.3f" )
			local se_st = string(`r(se)', "%6.3f" )
			local h_st = string(`r(h)', "%6.3f" )
			local N_st = string(`r(N)', "%6.0g" )
			local est = `r(est)'
			local tstat = `r(tstat)'
			local se = `r(se)'
			local h = `r(se)'
			local N = `r(N)'
			
			di "**** rd (`bidder_auction'); est:`est_st'; tstat:`tstat_st'; N:`N_st' ****"
			*qui replace tau_`runvar' = `r(est)' if thebidder == 1
			*qui replace tstat_`runvar' = `r(tstat)' if thebidder == 1
			*qui replace N_`runvar' = `r(N)' if thebidder == 1
			/*di "**** est:" `e(tau_bc)'
			di "**** est_l:" `e(tau_bc_l)'
			di "**** est_r:" `e(tau_bc_r)'
			di "**** se_r:" sqrt(Br[1,1])	
			di "***   h_r" `e(h_r)'*/		
			if "`ii'" != "nograph" {
				/* x軸評価点を得るためのlpoly*/
				cap drop xvar
				cap drop yvar
				local onebw = `r(h)'
				local bw_lpoly = ""
				if ustrregexm("`graphtableop'","onebw"){
					local bw_lpoly = "bw(`onebw')"
				}		
				lpoly `outcomevar' `runvar' if rank1_`sp' > 1 & rank1_`sp' < . & abs(`runvar') < .15 & tie1`sp' ~= 1 ///
					& abs(`outcomevar' + `scatter_outcomevar_offset' ) < .13, deg(1) `bw_lpoly' kernel(tri) gen(xvar yvar) nograph
				sort xvar
				*count if xvar < . /*かならず50になる（lpolyのデフォルトの評価点数は50だから*/
				qui replace xvar = 0 if _n == 50 + 1
				qui drop yvar
				/* 推定値を得るためのlpoly (推定値はyvarに格納)*/
				lpoly `outcomevar' `runvar' if rank1_`sp' > 1 & abs(`runvar') < .15 & tie1`sp' ~= 1 ///
					& abs(`outcomevar' + `scatter_outcomevar_offset') < .13, gen(yvar) at(xvar) `bw_lpoly' kernel(tri) deg(1) nograph
				
				twoway(scatter `outcomevar' `runvar' if `outcomevar' > 0 & abs(`runvar') < .15 ///
					& abs(`outcomevar' + `scatter_outcomevar_offset') < .13 & rank1_`sp' > 1 & tie1`sp' ~= 1, ///
					xlabel("`scatter_xlabel'") /*ytitle("`tileft'", orientation(horizontal))*/ ///
					xtitle("% Difference in `runvar_label'", margin(0 0 0 2)) ytitle("% Difference in `outcomevar_label'", margin(-1 -2 0 0) ///
						/*orientation(horizontal)*/) color(gs5%80) msize(`msz')) ///
					(scatter `outcomevar' `runvar' if `outcomevar' <= 0 & abs(`runvar') < .15 & tie1`sp' ~= 1 ///
						& abs(`outcomevar' + `scatter_outcomevar_offset') < .13 & rank1_`sp' > 1 , ///
						ylabel("`scatter_ylabel'", angle(0) format(%5.2g)) color(gs5%80) msize(`msz')) ///
					(line yvar xvar if abs(yvar+`scatter_outcomevar_offset')<.13 & abs(xvar)<.15 /*&tie1`sp' ~= 1*/,sort color(gs10) lwidth(thick)), /// 
						name(`gname') legend(off) title("`gtitle'", /*size(medsmall)*/) ///
							/*subtitle("tau:`tau_p'" , place(se) ring(0))*/ ///
							/*subtitle("{it:t}=`ts1p'" , place(se) ring(0))*/  graphregion(c(white)) ///
							t1title("{it:{&beta}}(se):`est_st'(`se_st')", place(ne) ring(0) size(small)) ///
							t2title("N=`N_st'; {it:t} =`tstat_st'; h=`h_st'", place(ne) ring(0) size(small)) ///
							xline(0,lpat("l") lcolor(black)) yline(0,lpat("l") lcolor(black)) ///
							xsc(`scatter_xsc') ysc(`scatter_ysc') xsize(4) ysize(4) plotregion(margin(tiny))
			}
		}
		/*scatter depvar indepvar if abs(depvar) < .2 & abs(indepvar) < .2 */
		*di "tau:`tau_p'"							
		*save ddd, replace
	restore
	return local tstat = `tstat'
	return local est = `est'
	return local se = `se'
	return local N = `N'
	return local h = `h'
end
*/






